package com.kcnet.qk.util;

import android.util.Log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by Administrator on 2018/5/18.
 */

public class RootShell {

    private static OutputStream outputStream;
    private static Process process;

    private static String TAP = "input tap %d %d";
    private static String SWIPE = "input swipe %d %d %d %d 150";
    private static String KEYENENT ="input keyevent %d";


    public static void getSu() {

        try {
            if(process == null){
                process = Runtime.getRuntime().exec("su");
                outputStream = process.getOutputStream();
            }
        } catch (Exception e) {
        } finally {

        }

    }
    /**
     * 执行命令并且输出结果
     */
    public static String execRootCmd(String cmd) {
        String result = "";
        DataOutputStream dos = null;
        DataInputStream dis = null;

        try {

            dos.writeBytes(cmd + " \n");
            dos.flush();
            dos.writeBytes("exit \n");
            dos.flush();
            String line = null;
            while ((line = dis.readLine()) != null) {
                Log.d("result", line);
                result += line;
            }
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    public static boolean execShellCmd(String cmd) {

        try {
            if(process == null){
                process = Runtime.getRuntime().exec("su");
                outputStream = process.getOutputStream();
            }
            DataOutputStream dos = new DataOutputStream(outputStream);
            dos.writeBytes(cmd + "\n");
            dos.flush();
          //  process.waitFor();
        } catch (Exception e) {
            return false;
        } finally {

        }
        return true;

    }

    /*
* @Description: 输入坐标进行模拟点击
* @Param: [x, y]
* @return: void
* @Author: 赵浩
* @Date: 2018-04-27 14:47
*/
    public static boolean click(int x, int y) {
        return execShellCmd(String.format(TAP, x, y));
    }
    public static boolean swipe(int startx, int startY,int endX,int endY) {
        return execShellCmd(String.format(SWIPE, startx, startY,endX,endY));
    }

    public static boolean keyevent(int key) {
        return execShellCmd(String.format(KEYENENT, key));
    }
}
